<template>
  <div class="tinymce-editor">
    <editor v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick"></editor>
  </div>
</template>
<script>
import axios from 'axios'
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import "tinymce/plugins/lists";
// import "tinymce/plugins/lineheight";
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/imagetools";
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/emoticons"; //表情插件
import 'tinymce/plugins/media'
import "tinymce/plugins/link"; //插入链接
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/anchor";
// import "tinymce/plugins/autosave"
import "tinymce/plugins/autoresize"; //内容自适应插件
// import {getUrl2} from '../utils/request.js'
export default {
  components: {
    Editor
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    // 基本路径，默认为空根目录，如果你的项目发布后的地址为目录形式，
    // 即abc.com/tinymce，baseUrl需要配置成tinymce，不然发布后资源会找不到
    baseUrl: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default:
        "print    preview searchreplace autolink directionality visualblocks visualchars  fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize lineheight formatpainter axupimgs"
    },
    toolbar: {
      type: [String, Array],
      default:
        "code  undo redo restoredraft  lineheight    pastetext  forecolor backcolor bold italic underline strikethrough link anchor alignleft aligncenter alignright alignjustify outdent indent  \
    styleselect formatselect fontselect fontsizeselect  bullist numlist  blockquote subscript superscript removeformat  \
    table image media charmap emoticons hr pagebreak insertdatetime print preview  fullscreen  bdmap indent2em  formatpainter axupimgs"
    }
  },
  data() {
    return {
      init: {
        language_url: "/tinymce/zh_CN.js",
        language: "zh_CN",
        skin_url: "/tinymce/skins/ui/oxide",
        emoticons_database_url: "/tinymce/emoticons/js/emojis.js",
        content_css: "/tinymce/skins/content/default/content.min.css",
        // skin_url: `${this.baseUrl}/tinymce/skins/ui/oxide-dark`, // 暗色系
        // content_css: `${this.baseUrl}/tinymce/skins/content/dark/content.css`, // 暗色系
        statusbar: false, // 隐藏编辑器底部的状态栏
        selector: "textarea", // change this value according to your HTML
        plugins: this.plugins,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        min_height: 500,
        toolbar: this.toolbar,
        branding: false,
        menubar: true,
        file_picker_types: 'media',
        file_picker_callback: (callback, value, meta)=> {
          if(meta.filetype == 'media'){  
            let input = document.createElement('input');//创建一个隐藏的input
            input.setAttribute('type', 'file');
            let that = this;
            input.onchange = function(){
              that.$Notice.info({
                  title: '上传文件',
                  desc:  '正在上传中。。。请稍等',
                  duration: 0
              });
              let file = this.files[0];//选取第一个文件
              console.log(file)
              const Fd = new FormData();
              const session_id = that.Cookies.get('session')
              Fd.append('files', file)
              Fd.append('session_id',session_id)
              let url = ''
              if(file.type == 'video/mp4'){
                 url = that.$videoApi
              }else{
                 url = that.$audioApi
              }
              axios.post(url, Fd)
              .then(res => {    
                  that.$Message.success('上传成功点击保存插入编辑器');  
                  that.$Notice.destroy()  
                  callback(that.$imgUrl + res.data.data, { title: file.name }) 
              })
              .catch(() => {
         
              })
            }
            //触发点击
            input.click();
          }
        },
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, success, failure) => {
          const Fd = new FormData();
          const session_id = this.Cookies.get('session')
          Fd.append('files', blobInfo.blob(), blobInfo.filename())
          Fd.append('session_id',session_id)
          axios.post(this.$imgApi, Fd)
          .then(res => {        
              console.log(res)
              success(this.$webUrl + res.data.data);
          })
          .catch(() => {

          })
        },
        audio_template_callback: function(data) {
            return '<audio autoplay  controls width="' + data.width + '" height="' + data.height 
            + '"' + (data.poster ? ' poster="' + data.poster + '"' : '')
            + ' controls="controls">\n' + '<source src="' + data.source + '"' 
            + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' 
            + (data.source ? '<source src="' + data.source + '"' 
            + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' : '') 
            + '</audio>';
        },
        video_template_callback: function(data) {
            console.log(data)
            return '<video preload="meta" x-webkit-airplay="true" webkit-playsinline="true" style="object-fit:fill;border:1px solid #ccc" width="' + data.width + '" height="' + data.height 
            + '"' + (data.poster ? ' poster="' + data.poster + '"' : '')
            + ' controls="controls">\n' + '<source src="' + data.source + '"' 
            + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' 
            + (data.source ? '<source src="' + data.source + '"' 
            + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' : '') 
            + '</video>';
        }
      },
      myValue: this.value
    };
  },
  mounted() {
    tinymce.init({});
  },
  methods: {
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = "";
    },
    onChage(e) {},
    async uploadImg(FormData) {
      let res = await this.$api2.upload_img(FormData);
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue;
    },
    myValue(newValue) {
      this.$emit("input", newValue);
    }
  }
};
</script>
<style scoped>
  .ivu-notice-notice{
     z-index: 100000 !important;
  }
</style>